package com.lxk.mall.pms.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.lxk.mall.pms.controller.app.vo.AppProductSpuDetailRespVO;
import com.lxk.mall.pms.controller.app.vo.AppProductSpuPageReqVO;
import com.lxk.mall.pms.controller.app.vo.AppProductSpuRespVO;
import com.lxk.mall.pms.domain.PmsProductSku;
import com.lxk.mall.pms.domain.PmsProductSpu;
import com.lxk.mall.pms.enums.ProductSpuStatusEnum;
import com.lxk.mall.pms.service.IPmsProductBrowseHistoryService;
import com.lxk.mall.pms.service.IPmsProductSkuService;
import com.lxk.mall.pms.service.IPmsProductSpuService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.lxk.mall.pms.enums.PmsErrorCodeConstants.SPU_NOT_ENABLE;
import static com.lxk.mall.pms.enums.PmsErrorCodeConstants.SPU_NOT_EXISTS;


/**
 * 商品接口
 */
@RestController
@RequestMapping("/product/spu")
@Validated
@RequiredArgsConstructor
public class AppProductSpuController {

    private final IPmsProductSpuService productSpuService;

    private final IPmsProductSkuService productSkuService;

    private final IPmsProductBrowseHistoryService productBrowseHistoryService;

//    private final MemberLevelApi memberLevelApi;

//    private final MemberUserApi memberUserApi;

    /**
     * 获得商品列表
     * @param ids 编号列表
     * @return
     */
    @GetMapping("/list-by-ids")
    public R<List<AppProductSpuRespVO>> getSpuList(@RequestParam("ids") Set<Long> ids) {
        List<PmsProductSpu> list = productSpuService.getSpuList(ids);
        if (CollUtil.isEmpty(list)) {
            return R.ok(Collections.emptyList());
        }

        // 拼接返回
        list.forEach(spu -> spu.setSalesCount(spu.getSalesCount() + spu.getVirtualSalesCount()));
        List<AppProductSpuRespVO> voList = list.stream().map(e -> {
            AppProductSpuRespVO vo = new AppProductSpuRespVO();
            BeanUtil.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList());
        //todo 处理 vip 价格
        //MemberLevelRespDTO memberLevel = getMemberLevel();
        //voList.forEach(vo -> vo.setVipPrice(calculateVipPrice(vo.getPrice(), memberLevel)));
        return R.ok(voList);
    }

    /**
     * 获得商品分页
     * @param pageVO
     * @return
     */
    @GetMapping("/page")
    public TableDataInfo<AppProductSpuRespVO> getSpuPage(@Valid AppProductSpuPageReqVO pageVO) {
        TableDataInfo<PmsProductSpu> pageResult = productSpuService.getSpuPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getRows())) {
            return TableDataInfo.build();
        }

        // 拼接返回
        pageResult.getRows().forEach(spu -> spu.setSalesCount(spu.getSalesCount() + spu.getVirtualSalesCount()));
        List<AppProductSpuRespVO> voPageResult = pageResult.getRows().stream().map(e -> {
            AppProductSpuRespVO vo = new AppProductSpuRespVO();
            BeanUtil.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList());
        //todo 处理 vip 价格
//        MemberLevelRespDTO memberLevel = getMemberLevel();
//        voPageResult.getList().forEach(vo -> vo.setVipPrice(calculateVipPrice(vo.getPrice(), memberLevel)));
        TableDataInfo dataInfo = new TableDataInfo();
        BeanUtil.copyProperties(pageResult, dataInfo);
        dataInfo.setRows(voPageResult);
        return dataInfo;
    }

    /**
     * 获得商品明细
     * @param id 编号
     * @return
     */
    @GetMapping("/get-detail")
    public R<AppProductSpuDetailRespVO> getSpuDetail(@RequestParam("id") Long id) {
        // 获得商品 SPU
        PmsProductSpu spu = productSpuService.queryById(id);
        if (spu == null) {
            throw new ServiceException(SPU_NOT_EXISTS);
        }
        if (!ProductSpuStatusEnum.isEnable(spu.getStatus())) {
            throw new ServiceException(SPU_NOT_ENABLE);
        }
        // 获得商品 SKU
        List<PmsProductSku> skus = productSkuService.getSkuListBySpuId(spu.getId());

        // 增加浏览量
        productSpuService.updateBrowseCount(id, 1);
        // 保存浏览记录
        productBrowseHistoryService.createBrowseHistory(LoginHelper.getUserId(), id);

        // 拼接返回
        spu.setBrowseCount(spu.getBrowseCount() + spu.getVirtualSalesCount());

        AppProductSpuDetailRespVO spuVO = new AppProductSpuDetailRespVO();
        BeanUtils.copyProperties(spu, spuVO);

        if (CollUtil.isNotEmpty(skus)) {
            List<AppProductSpuDetailRespVO.Sku> skuList = skus.stream().map(sku -> {
                AppProductSpuDetailRespVO.Sku voSku = new AppProductSpuDetailRespVO.Sku();
                BeanUtils.copyProperties(sku, voSku);
                return voSku;
            }).collect(Collectors.toList());
            spuVO.setSkus(skuList);
        }
        //todo 处理 vip 价格
        //MemberLevelRespDTO memberLevel = getMemberLevel();
        //spuVO.setVipPrice(calculateVipPrice(spuVO.getPrice(), memberLevel));
        return R.ok(spuVO);
    }

//    private MemberLevelRespDTO getMemberLevel() {
//        Long userId = LoginHelper.getUserId();
//        if (userId == null) {
//            return null;
//        }
//        MemberUserRespDTO user = memberUserApi.getUser(userId);
//        if (user.getLevelId() == null || user.getLevelId() <= 0) {
//            return null;
//        }
//        return memberLevelApi.getMemberLevel(user.getLevelId());
//    }

    /**
     * 计算会员 VIP 优惠价格
     *
     * @param price       原价
     * @param memberLevel 会员等级
     * @return 优惠价格
     */
//    public Integer calculateVipPrice(Integer price, MemberLevelRespDTO memberLevel) {
//        if (memberLevel == null || memberLevel.getDiscountPercent() == null) {
//            return 0;
//        }
//        Integer newPrice = price * memberLevel.getDiscountPercent() / 100;
//        return price - newPrice;
//    }

    // TODO 芋艿：商品的浏览记录；
}
